<template>
  <div class="risk-alerts">
    <!-- 风控提醒卡片 -->
    <el-card v-if="alerts.length > 0" class="risk-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="warning-icon"><Warning /></el-icon>
            <span class="title">风控提醒</span>
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="badge" />
          </div>
          <div class="header-right">
            <el-button 
              size="small" 
              text 
              @click="markAllAsRead"
              :disabled="unreadCount === 0"
            >
              全部已读
            </el-button>
            <el-button size="small" text @click="refreshAlerts">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <div class="alerts-list">
        <div 
          v-for="alert in alerts" 
          :key="alert.id"
          class="alert-item"
          :class="[`alert-${alert.type}`, `level-${alert.level}`]"
        >
          <div class="alert-icon">
            <el-icon v-if="alert.type === 'warning'"><Warning /></el-icon>
            <el-icon v-else-if="alert.type === 'error'"><CircleClose /></el-icon>
            <el-icon v-else><InfoFilled /></el-icon>
          </div>
          
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-message">{{ alert.message }}</div>
            <div v-if="alert.suggestion" class="alert-suggestion">
              <el-icon><Lightbulb /></el-icon>
              <span>{{ alert.suggestion }}</span>
            </div>
            <div class="alert-data" v-if="alert.data">
              <span v-if="alert.data.currentRate">
                当前: {{ alert.data.currentRate }}% | 标准: {{ alert.data.standardRate }}%
              </span>
              <span v-if="alert.data.currentTime">
                当前: {{ alert.data.currentTime }}{{ alert.data.unit }} | 标准: {{ alert.data.standardTime }}{{ alert.data.unit }}
              </span>
            </div>
          </div>
          
          <div class="alert-actions">
            <el-button 
              size="small" 
              text 
              @click="markAsRead(alert.id)"
              v-if="!alert.read"
            >
              标记已读
            </el-button>
            <div class="alert-time">
              {{ formatTime(alert.createTime) }}
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 无风控提醒时的状态 -->
    <el-card v-else class="risk-card no-alerts" shadow="hover">
      <div class="no-alerts-content">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <div class="no-alerts-title">风控状态正常</div>
        <div class="no-alerts-desc">当前各项指标均在正常范围内</div>
        <el-button size="small" text @click="refreshAlerts">
          <el-icon><Refresh /></el-icon>
          刷新检查
        </el-button>
      </div>
    </el-card>

    <!-- 风控统计数据 -->
    <el-card v-if="showStatistics && statistics" class="statistics-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">风控指标</span>
        </div>
      </template>

      <div class="statistics-grid">
        <div class="stat-item">
          <div class="stat-label">退款率</div>
          <div class="stat-value" :class="getStatClass(statistics.refundRate)">
            {{ statistics.refundRate.current }}%
            <el-icon v-if="statistics.refundRate.trend === 'up'" class="trend-up"><ArrowUp /></el-icon>
            <el-icon v-else-if="statistics.refundRate.trend === 'down'" class="trend-down"><ArrowDown /></el-icon>
          </div>
          <div class="stat-standard">标准: ≤{{ statistics.refundRate.standard }}%</div>
        </div>

        <div class="stat-item">
          <div class="stat-label">响应时间</div>
          <div class="stat-value" :class="getStatClass(statistics.responseTime)">
            {{ statistics.responseTime.current }}分钟
            <el-icon v-if="statistics.responseTime.trend === 'up'" class="trend-up"><ArrowUp /></el-icon>
            <el-icon v-else-if="statistics.responseTime.trend === 'down'" class="trend-down"><ArrowDown /></el-icon>
          </div>
          <div class="stat-standard">标准: ≤{{ statistics.responseTime.standard }}分钟</div>
        </div>

        <div class="stat-item">
          <div class="stat-label">客户满意度</div>
          <div class="stat-value" :class="getStatClass(statistics.customerSatisfaction)">
            {{ statistics.customerSatisfaction.current }}星
            <el-icon v-if="statistics.customerSatisfaction.trend === 'up'" class="trend-up"><ArrowUp /></el-icon>
            <el-icon v-else-if="statistics.customerSatisfaction.trend === 'down'" class="trend-down"><ArrowDown /></el-icon>
          </div>
          <div class="stat-standard">标准: ≥{{ statistics.customerSatisfaction.standard }}星</div>
        </div>

        <div class="stat-item">
          <div class="stat-label">订单完成率</div>
          <div class="stat-value" :class="getStatClass(statistics.orderCompletion)">
            {{ statistics.orderCompletion.current }}%
            <el-icon v-if="statistics.orderCompletion.trend === 'up'" class="trend-up"><ArrowUp /></el-icon>
            <el-icon v-else-if="statistics.orderCompletion.trend === 'down'" class="trend-down"><ArrowDown /></el-icon>
          </div>
          <div class="stat-standard">标准: ≥{{ statistics.orderCompletion.standard }}%</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Warning,
  CircleClose,
  InfoFilled,
  Lightbulb,
  Refresh,
  CircleCheck,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { getRiskAlerts, markAlertAsRead, getRiskStatistics, markMultipleAlertsAsRead } from '@/api/risk'

// Props
const props = defineProps({
  showStatistics: {
    type: Boolean,
    default: true
  },
  autoRefresh: {
    type: Boolean,
    default: false
  },
  refreshInterval: {
    type: Number,
    default: 300000 // 5分钟
  }
})

// 响应式数据
const alerts = ref([])
const statistics = ref(null)
const loading = ref(false)

// 计算属性
const unreadCount = computed(() => {
  return alerts.value.filter(alert => !alert.read).length
})

// 方法
const fetchAlerts = async () => {
  try {
    const response = await getRiskAlerts()
    if (response.code === 200) {
      alerts.value = response.data.alerts || []
    }
  } catch (error) {
    console.error('获取风控提醒失败:', error)
  }
}

const fetchStatistics = async () => {
  if (!props.showStatistics) return
  
  try {
    const response = await getRiskStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取风控统计失败:', error)
  }
}

const markAsRead = async (alertId) => {
  try {
    await markAlertAsRead(alertId)
    const alert = alerts.value.find(a => a.id === alertId)
    if (alert) {
      alert.read = true
    }
    ElMessage.success('已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

const markAllAsRead = async () => {
  const unreadAlerts = alerts.value.filter(alert => !alert.read)
  if (unreadAlerts.length === 0) return

  try {
    const alertIds = unreadAlerts.map(alert => alert.id)
    await markMultipleAlertsAsRead(alertIds)
    
    alerts.value.forEach(alert => {
      alert.read = true
    })
    
    ElMessage.success('全部标记为已读')
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  }
}

const refreshAlerts = async () => {
  loading.value = true
  try {
    await Promise.all([fetchAlerts(), fetchStatistics()])
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

const getStatClass = (stat) => {
  if (!stat) return ''
  
  const { current, standard, unit } = stat
  
  // 根据不同指标判断是否超标
  if (unit === 'percent' || stat === statistics.value?.refundRate || stat === statistics.value?.orderCompletion) {
    // 退款率：越低越好，订单完成率：越高越好
    if (stat === statistics.value?.refundRate) {
      return current > standard ? 'stat-danger' : 'stat-success'
    } else {
      return current < standard ? 'stat-danger' : 'stat-success'
    }
  } else if (stat === statistics.value?.responseTime) {
    // 响应时间：越低越好
    return current > standard ? 'stat-danger' : 'stat-success'
  } else if (stat === statistics.value?.customerSatisfaction) {
    // 客户满意度：越高越好
    return current < standard ? 'stat-danger' : 'stat-success'
  }
  
  return ''
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return `${Math.floor(diff / 86400000)}天前`
}

// 生命周期
onMounted(async () => {
  await Promise.all([fetchAlerts(), fetchStatistics()])
  
  // 自动刷新
  if (props.autoRefresh) {
    setInterval(() => {
      fetchAlerts()
      fetchStatistics()
    }, props.refreshInterval)
  }
})

// 暴露方法给父组件
defineExpose({
  refreshAlerts,
  fetchAlerts,
  fetchStatistics
})
</script>

<style scoped>
.risk-alerts {
  .risk-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .warning-icon {
          color: #e6a23c;
          font-size: 18px;
        }
        
        .title {
          font-weight: 600;
          color: #303133;
        }
      }
      
      .header-right {
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .alerts-list {
    .alert-item {
      display: flex;
      gap: 12px;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 12px;
      border-left: 4px solid;
      
      &.alert-warning {
        background: #fdf6ec;
        border-left-color: #e6a23c;
      }
      
      &.alert-error {
        background: #fef0f0;
        border-left-color: #f56c6c;
      }
      
      &.alert-success {
        background: #f0f9ff;
        border-left-color: #67c23a;
      }
      
      &.level-high {
        border-left-width: 6px;
      }
      
      .alert-icon {
        font-size: 20px;
        margin-top: 2px;
        
        .el-icon {
          color: inherit;
        }
      }
      
      .alert-content {
        flex: 1;
        
        .alert-title {
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .alert-message {
          color: #606266;
          line-height: 1.5;
          margin-bottom: 8px;
        }
        
        .alert-suggestion {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #909399;
          font-size: 13px;
          margin-bottom: 8px;
          
          .el-icon {
            color: #e6a23c;
          }
        }
        
        .alert-data {
          font-size: 12px;
          color: #909399;
          background: rgba(0, 0, 0, 0.05);
          padding: 4px 8px;
          border-radius: 4px;
          display: inline-block;
        }
      }
      
      .alert-actions {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 8px;
        
        .alert-time {
          font-size: 12px;
          color: #c0c4cc;
        }
      }
    }
  }
  
  .no-alerts {
    .no-alerts-content {
      text-align: center;
      padding: 40px 20px;
      
      .success-icon {
        font-size: 48px;
        color: #67c23a;
        margin-bottom: 16px;
      }
      
      .no-alerts-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 8px;
      }
      
      .no-alerts-desc {
        color: #909399;
        margin-bottom: 20px;
      }
    }
  }
  
  .statistics-card {
    .statistics-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 20px;
      
      .stat-item {
        text-align: center;
        padding: 16px;
        border-radius: 8px;
        background: #fafafa;
        
        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-bottom: 8px;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          margin-bottom: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 4px;
          
          &.stat-success {
            color: #67c23a;
          }
          
          &.stat-danger {
            color: #f56c6c;
          }
          
          .trend-up {
            color: #f56c6c;
            font-size: 16px;
          }
          
          .trend-down {
            color: #67c23a;
            font-size: 16px;
          }
        }
        
        .stat-standard {
          font-size: 12px;
          color: #c0c4cc;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .risk-alerts {
    .alert-item {
      flex-direction: column;
      gap: 8px;
      
      .alert-actions {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
    }
    
    .statistics-grid {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}
</style>
